package com.banmao.CarlCamp.Day09;

/**
 * https://leetcode.cn/problems/ti-huan-kong-ge-lcof/
 */
public class Offer05 {

    public String replaceSpace(String s) {
        if (s == null || s.length() == 0) {
            return s;
        }

        StringBuilder sb = new StringBuilder(s);
        for (char c : s.toCharArray()) {
            if (c == ' ') {
                sb.append("  ");
            }
        }

        // 双指针从后往前遍历
        int fast = s.length() - 1, slow = sb.length() - 1;
        while (fast >= 0) {
            if (sb.charAt(fast) == ' ') {
                // 快指针指向空格时，慢指针进行填充
                sb.setCharAt(slow--, '0');
                sb.setCharAt(slow--, '2');
                sb.setCharAt(slow--, '%');
                fast--;
            } else {
                // 进行替换并移动指针
                sb.setCharAt(slow, sb.charAt(fast));
                fast--;
                slow--;
            }
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        Offer05 offer05 = new Offer05();
        System.out.println(offer05.replaceSpace("We are happy."));
    }

}
